package com.newmuis.open.codeeval.easy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * CodeEval.com > Easy Challenges > Sum of Integers from File
 * 
 * Description:
 * 
 * Print out the sum of integers read from a file.
 * 
 * Input sample:
 * 
 * The first argument to the program will be a text file containing a positive integer, one per
 * line. e.g.
 * 
 * 5
 * 12
 * 
 * Output sample:
 * 
 * Print out the sum of all the integers read from the file. e.g.
 * 
 * 17
 * 
 * @author Jonathan Newmuis (jon@newmuis.com)
 * @category easy
 * 
 */
public class sumint {
	/**
	 * @param args should contain only one CLI argument: the path to an input file which specifies
	 *            the input in the defined format.
	 * @throws IOException if there is a problem reading the given input file.
	 */
	public static void main(final String[] args) throws IOException {
		// Verify input argument length.
		if (args.length < 1) {
			throw new RuntimeException("Must specify input file path.");
		} else if (args.length > 1) {
			throw new RuntimeException("Illegal input arguments specified.");
		}

		// Read file from specified path.
		final BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
		String line;
		int sum = 0;

		while ((line = reader.readLine()) != null) {
			try {
				// Get the value of "n".
				sum += Integer.parseInt(line);
			} catch (final NumberFormatException e) {
				throw new RuntimeException("Input file contained non-numeric arguments.");
			}
		}

		// Output the sum to System.out.
		System.out.println(sum);
	}
}
